package com.example.origin.redis.utils;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;


@Slf4j
public class ProtoStuffSerializer<T> implements RedisSerializer<T> {

    @Override
    public byte[] serialize(T object) throws SerializationException {
        if (object == null) {
            return null;
        }
        return ProtostuffUtil.serialize(new BytesWrapper<>(object));
    }

    @Override
    public T deserialize(byte[] bytes) throws SerializationException {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        BytesWrapper deserialize = ProtostuffUtil.deserialize(bytes, BytesWrapper.class);
        Object value = deserialize.getValue();
        return (T) value;

    }


    @Getter
    @AllArgsConstructor
    static class BytesWrapper<T> {
        private T value;
    }
}
